package com.example.demo01.Socket.Server;

import com.example.demo01.Socket.NettyConstant;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;


@Component
@Slf4j
public class NettyServer {


    @Resource
    private NettyConfig nettyConfig;

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    private ChannelFuture future;
//    @PostConstruct
    public void start() throws Exception {
        // 配置服务端的NIO线程组


        ServerBootstrap b = new ServerBootstrap();


        //
        //需要两个线程组
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new NettyServerChannelInitializer());


        int port=nettyConfig.getPort();
        // 绑定端口，同步等待成功
         future = b.bind(port).sync();
        log.info("Netty server start  port " + port);
    }



    @PreDestroy
    public  void close() throws InterruptedException {
//
        if(future!=null){

            log.info("shut downing  server ");
            bossGroup.shutdownGracefully().syncUninterruptibly();
            workerGroup.shutdownGracefully().syncUninterruptibly();
            future.channel().closeFuture().sync();
            log.info("shut down  server ");
        }

    }


}
